<template>
  <div class="systemInfo">
    <span>CPU使用率 : {{ systemInfo.cpu_percent }} %</span>
    <span>GPU使用率 : {{ systemInfo.gpu_percent }} %</span>
    <span>内存占用率 : {{ systemInfo.memory_percent }} %</span>
    <span>硬盘剩余容量/总容量 : {{ ((systemInfo.disk_free)/(1024*1024*1024)).toFixed(2) }} G/{{ (systemInfo.disk_total/(1024*1024*1024)).toFixed(2) }} G</span>
  </div>
  <div class="stopAll">
      <el-button type="danger" @click="stopAll">停止所有参估</el-button>
  </div>
    <div class="el-table_body">
          <el-table 
            max-height="88vh" style="width: 100% ; font-size: 14px " border
            @selection-change="handleSelectionChange"
            :data="tableData" 
            highlight-current-row
            ref="singleTableRef">
            <el-table-column type="selection"  width="60rem" align="center"/>
            <el-table-column prop="pathid" label="DDC通道号" align="center"/>
            <el-table-column prop="pathstate" label="参估状态" width="120rem" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.pathstate == 4 ||scope.row.pathstate == 3?'success':'danger'">
                   {{ scope.row.pathstate == 4 ||scope.row.pathstate == 3?"进行中":"停止" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ch0_freq" label="通道0频点(Hz)" align="center"/>
            <el-table-column prop="ch1_freq" label="通道1频点(Hz)" align="center"/>
            <el-table-column prop="ch2_freq" label="通道2频点(Hz)" align="center"/>
            <el-table-column prop="ch3_freq" label="通道3频点(Hz)" align="center"/>
            <el-table-column prop="sample_rate" label="采样率(Hz)"  align="center"/>
            <el-table-column prop="estimate_algotype" label="参估算法" align="center">
              <template #default="scope">  
                {{ scope.row.estimate_algotype == 0?"FFT":"自定义" }}
              </template>
            </el-table-column>
            <el-table-column prop="time_range" label="时差范围 (us)" align="center"/>
            <el-table-column prop="freq_range" label="频差范围 (Hz)" align="center"/>
            <el-table-column prop="estimate_bandwidth" label="带宽(Hz)"  align="center"/>
            <el-table-column prop="related_len" label="相关长度(ms)"  align="center"/>
            <el-table-column prop="judge_threshold" label="判决门限"  align="center"/>
            <el-table-column prop="up_factor" label="插值倍数"  align="center"/>
            <el-table-column prop="count" label="参估计个数" align="center"/>
            <el-table-column prop="time_ms" label="参估时间(ms)"  align="center"/>
            <el-table-column fixed="right" label="操作" width="200rem" align="center">
              <template #default="scope">
                <!-- <el-button round type="danger" size="small" 
                @click="stopOnePath(scope.row.pathid)" :disabled=" scope.row.pathstate == 4 ||scope.row.pathstate == 3 ?false:true" >停止</el-button> -->
                <el-button type="primary" size="small" round dark=true
                @click="openDialog('修改检测参数',scope.row.pathid)">修改</el-button>
                <el-button round type="success" size="small" 
                @click="startOnePath(scope.row.pathid)" :disabled="scope.row.pathstate == 4 ||scope.row.pathstate == 3?true:false">开始</el-button>
              </template>
            </el-table-column>
          </el-table>
    </div>
    <el-dialog
          v-model="dialog.visible"
          :title="dialog.title"
          :width="dialog.width"
          append-to-body
          center
          draggable="true"
        >
            <el-form label-width="4.2rem">
              <el-form-item label="DDC通道号">
                 {{ currentDDC_data.pathid }}
              </el-form-item>
              <el-form-item label="参估算法" prop="estimate_algotype">
                <el-select v-model="currentDDC_data.estimate_algotype">
                  <el-option 
                  v-for="item in estimateestimate_algotypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  ></el-option>
                  
                </el-select>
              </el-form-item>
              <el-form-item label="时差范围" prop="time_range">
                <el-input type="number"
                  v-model.number="currentDDC_data.time_range"
                />
              </el-form-item>
              <el-form-item label="频差范围" prop="freq_range">
                <el-input type="number"
                  v-model.number="currentDDC_data.freq_range"
                />
              </el-form-item>
              
              <el-form-item label="带宽" prop="estimate_bandwidth">
                <el-input type="number"
                  v-model.number="currentDDC_data.estimate_bandwidth"
                />
              </el-form-item>
              <el-form-item label="相关长度" prop="related_len">
                <el-input type="number"
                  v-model.number="currentDDC_data.related_len"
                />
              </el-form-item>
              <el-form-item label="判决门限" prop="judge_threshold">
                <el-input type="number"
                  v-model.number="currentDDC_data.judge_threshold"
                />
              </el-form-item>
              <el-form-item label="插值倍数" prop="up_factor">
                <el-input type="number"
                  v-model.number="currentDDC_data.up_factor"
                />
              </el-form-item>
            </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="confirmModify">确认修改</el-button>
              <el-button @click="cancelModify">取消修改</el-button>
            </span>
          </template>
    </el-dialog>
</template>

<script lang="ts" setup>
  import '../assets/font_satelite/iconfont.css'
  import { ref, reactive, onMounted,onUnmounted } from 'vue'
  import { ElTable,ElMessage } from 'element-plus'
  import { Download,Upload,Open,TurnOff } from '@element-plus/icons-vue'
  import { Row } from 'element-plus/es/components/table-v2/src/components';
  import EstimateApi from '../apis/estimateHttp.js'
  const activeIndex = ref('1')
  const estimateSocket = "/estimateSocket"
  const tableData = ref([
  {
    pathid: 0,
    pathstate:3,
  },{
    pathid: 1,
    pathstate:0,
  },{
    pathid: 2,
    pathstate:1,
  },{
    pathid: 3,
    pathstate:1,
  },{
    pathid: 4,
    pathstate:0,
  },
  {
    pathid: 5,
    pathstate:1,
  },{
    pathid: 6,
    pathstate:0,
  },{
    pathid: 7,
    pathstate:0,
  },{
    pathid: 8,
    pathstate:1,
  },{
    pathid: 9,
    pathstate:0,
  },{
    pathid: 10,
    pathstate:1,
  },{
    pathid: 11,
    pathstate:0,
  },{
    pathid: 12,
    pathstate:0,
  },{
    pathid: 13,
    pathstate:0,
  },{
    pathid: 14,
    pathstate:0,
  },{
    pathid: 15,
    pathstate:0,
  },{
    pathid: 16,
    pathstate:0,
  },
  ])
  interface oneDDC_data {
      pathid: number
      pathstate: number
      ch0_freq: number
      ch1_freq: number
      ch2_freq: number
      ch3_freq: number
      estimate_algotype:number
      time_range:number
      freq_range:number
      estimate_bandwidth:number
      sample_rate:96000,
      related_len:0,
      judge_threshold:0,
      up_factor:0
      count: number
      time_ms: number
  }
  const systemInfo = reactive({
    cpu_percent:0,
    field:-1,
    gpu_percent:0,
    memory_percent:0,
    disk_free:0,
    disk_total:0
  })
  const dialog = reactive({
    visible:false,
    type:"singlePath-form",
    width:400,
    title:""
  })  
  const currentDDC_data = ref({
    pathid: 0,
    estimate_algotype:0,
    time_range:30000,
    freq_range:5000,
    estimate_bandwidth:5000,
    sample_rate:96000,
    related_len:0,
    judge_threshold:0,
    up_factor:0
  })

  const ws = ref() //socket
  let rec
  let isConnect = false
  let checkMsg = "heartbeat"
  const CreateWebSocket = () => {
    try {
      initWebsocket()
    }catch (e){
      console.log("参估尝试连接失败");
      // reConnect()
    }
  }
  const initWebsocket = () => {
    const svrHost = window.location.hostname
    let url = 'ws://192.168.1.22:9888'
  
    if(svrHost.length < 1)
      url = "ws://192.168.1.22:9888"

    if("WebSocket" in window)
      ws.value = new WebSocket(`ws://${window.location.host}/estimateWS`)
    
    ws.value.onopen = () => {
      console.log('[参估ws.onopen]:enter')
      isConnect = true     
    }

    ws.value.onmessage =  (e) => {
      let data = JSON.parse(e.data)
      if(data && "field" in data) {
        if(data["field"] === 2){
          tableData.value.forEach((item) => {
            if(item.pathid === data["pathid"]){
              item.estimate_algotype = data["estimate_algotype"]
              item.time_range = data["time_range"]
              item.freq_range = data["freq_range"]
              item.estimate_bandwidth = data["estimate_bandwidth"]
              
            }
          })
        }else if(data["field"] === 3){
          tableData.value.forEach((item) => {
            if(item.pathid === data["pathid"]){
              item.pathstate = data["pathstate"]
              item.count = data["count"]
              item.time_ms = data["time_ms"]
            }
          })
        }else if(data["field"] === 4){
          systemInfo.cpu_percent = data["cpu_percent"]
          systemInfo.disk_free = data["disk_free"]
          systemInfo.disk_total = data["disk_total"]
          systemInfo.gpu_percent = data["gpu_percent"]
          systemInfo.memory_percent = data["memory_percent"]
        }
      }
    }
  
    ws.value.onclose = (e) => {    
      console.log('[参估ws.onclose]: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
      isConnect = false
      if(e.wasClean) console.log('WebSocket连接已正常关闭'); 
      else ElMessage.error("websocket与参估CS软件未连接，参估CS软件可能已关闭，尝试重启参估并刷新网页")
    }
    
    ws.value.onerror = (e) => {
      console.log("[参估ws.onerror]:");
      // reConnect()
    }
  }
  let reConnect = () => {
    console.log("参估-尝试重新连接");
    if (isConnect) return; //如果已经连上就不在重连了
    rec && clearTimeout(rec);
    rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
      CreateWebSocket();
    }, 30000);
  };
  onMounted(async () => {
    CreateWebSocket()
    try{
      const getTableData = await EstimateApi.getAllData()
           
      tableData.value = getTableData["all"]    
      
    }catch(error){
      // reConnect()
    }   
  })
  onUnmounted(async () => {
    ws.value.close()
  })

  const estimateestimate_algotypes = [{
    value:0,
    label:"FFT"
  },{
    value:1,
    label:"SM求和法"
  },{
    value:2,
    label:"自定义"
  }]
  //确认修改
  const confirmModify = async () => {
  
    //向服务器提交修改的表格数据
    const modifyData = EstimateApi.postModify(currentDDC_data.value)
    //修改本地表格数组数据  
    dialog.visible = false
  }
  //取消修改,关闭弹窗即可
  const cancelModify = () => {
    dialog.visible = false
  }
  const currentRow = ref()
  const singleTableRef = ref<InstanceType<typeof ElTable>>()
  const handleCurrentChange = (val: oneDDC_data | undefined) => {
    currentRow.value = val
  
  }
  
  //TODO 编辑某行弹出弹窗  
  async function openDialog(type:string,id:number){
      dialog.visible = true;
      dialog.type = type;
        
      if(id >= 0 && id <= 63){
        dialog.title = "修改参估参数";                       
        Object.assign(currentDDC_data.value,{...tableData.value[id]})

      }
  }
  //TODO 停止某行
  async function stopOnePath(id:number) {
    //后端接口发送要停止的DDC通道号,并接收返回的状态更新表格状态栏
    try {
      const sendStatus = await EstimateApi.postStop(id)
    }catch(err){
      console.log(Error);      
    }
  }
  //TODO 开始某行
  async function startOnePath(id:number){
    //调用后端接口传要开始的DDC通道号，并接收返回状态更改状态栏显示
    try {
      const sendStatus = await EstimateApi.postStart(id)
      
    }catch(err){
      console.log(Error);    
    }
  }
  //停止当前所有通道的检测
  const stopAll = async () => {
    EstimateApi.postStopAll()
  }
  const multiSelection = ref([])//用于加载所有要开始/停止的ID集合
  //处理选择的行改变
  const handleSelectionChange = (selection:any) => {
    multiSelection.value = selection.map((item:any) => item.pathid)
  }
  //TODO 开始多行
  async function startMultiPaths() {
    for(const item in multiSelection.value) console.log(item);
    
  }
  //TODO 停止多行
  async function stopMultiPaths() {
    for(const item in multiSelection.value) console.log(item);
    
  }
  //导出json文件
  const handleExport = () =>{
    //TODO 调用接口请求配置文件数据
    const fileName = "config.json"
    const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=uft-8"
    const data = JSON.stringify(tableData.value)
    const blob = new Blob([data],{type:fileType})
    const downloadUrl = window.URL.createObjectURL(blob)
    const downloadLink = document.createElement("a")
    downloadLink.href = downloadUrl
    downloadLink.download = fileName

    document.body.appendChild(downloadLink)
    downloadLink.click()

    document.body.removeChild(downloadLink)
    window.URL.revokeObjectURL(downloadUrl)
  }
  //导入json文件
  const handleImport = () => {

  }
</script>

<style>
.systemInfo {
  display: flex;
  margin: 0.4rem 0;
  padding: 0rem 0.4rem;
  height:1.6rem;
  font-size: 0.8rem;
  background-color: #909399;
  color: aliceblue;
}
.systemInfo > span {
  flex: 1;
}

</style>